package com.peng.leetcode.array;

/**
 * MaxAreaOfIsland
 * 剑指 Offer II 105. 岛屿的最大面积
 * https://leetcode.cn/problems/ZL6zAn/
 *
 * @author: lupeng6
 * @create: 2023/2/18 19:24
 */
public class MaxAreaOfIsland {

    private boolean[][] visited;

    public int maxAreaOfIsland(int[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        visited = new boolean[grid.length][grid[0].length];
        int ans = Integer.MIN_VALUE;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                ans = Math.max(ans, dfs(grid, i, j));
            }
        }
        return ans;
    }

    private int dfs(int[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length
                || j >= grid[i].length || grid[i][j] != 1
                || visited[i][j]) {
            return 0;
        }
        int ans = 1;
        visited[i][j] = true;
        int[][] options = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        for (int[] option : options) {
            int nextI = i + option[0];
            int nextJ = j + option[1];
            ans += dfs(grid, nextI, nextJ);
        }
        return ans;
    }
}
